package gwtgaetools.client.ui;

import gwtgaetools.client.ItemManager;

import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.user.client.ui.Widget;

public class EditableTextArea<M> {

	public int MIN_WIDTH = 200; // PX
	
	public SmartTextArea<M> editor = new SmartTextArea<M>();
	public SmartInlineLabel<M> label = new SmartInlineLabel<M>();

	public boolean inEditingMode = false;
	
	public EditableTextArea() {}
	
	public EditableTextArea(ItemManager<M> m) {
		setItem(m);
		editor.setVisibleLines(10);
	}
	
	public EditableTextArea(ItemManager<M> m, String s) {
		this(m);
		addTextboxStyle(s);
	}
	
	public void addKDH(KeyDownHandler kdh) {
		editor.addKeyDownHandler(kdh);
	}
	
	public void setEditingMode(boolean b) {
		if (b) {
			editor.setWidth(Math.max(label.getOffsetWidth(), MIN_WIDTH) + "px");
			editor.setVisibleLines(7);
		} else {
			editor.setText(label.getText());
		}
		
		inEditingMode = b;
			
	}
	
	public Widget getActiveWidget() {
		if (inEditingMode)
			return editor;
		else
			return label;
	}

	public String getText() {
		if (inEditingMode)
			return editor.getText();
		else
			return label.getText();
	}
	
	public void setItem(ItemManager<M> m) {
		m.registerListener(editor);
		m.registerListener(label);
	}

	public void addTextboxStyle(String s) {
		editor.addStyleDependentName(s);
		label.addStyleDependentName(s);
	}
	
	public boolean hasNewValue() {
		return !editor.getText().equals(label.getText());
	}

	public void addClickHandler(ClickHandler clickHandler) {
		label.addClickHandler(clickHandler);
	}
}
